<template>
  <view v-if="curPage !== 'map'">
    <uni-nav-bar title="车用尿素外卖单" left-icon="left" @clickLeft="navBack" statusBar></uni-nav-bar>
    <!-- 步骤导航 -->
    <stepNav></stepNav>
    <!-- 安蓝头部标题 -->
    <CodeTop></CodeTop>
    <!-- 普通用户头部 -->
    <view class="package" v-if="information.team_id === 0">
      <!-- 金额显示 -->
      <PriceList :fill_price="Pricegroup.wechat" :vip_price="Pricegroup.money" :locationName="positionText"
        :type="'investors'" :PaymentMethod="PaymentMethod"></PriceList>
    </view>
    <!-- 不同身份团显示的头部样式及加注金额 -->
    <view class="package" v-else style="padding: 0px 0px 20rpx 0px;">
      <!-- 团头部信息 -->
      <TeamTop :teamImg="Pricegroup.image" :TeamType="Pricegroup.type" :teamDay="Pricegroup.day"></TeamTop>
      <view style="width: 96%;margin: -15rpx auto 0px;">
        <!-- 金额显示 -->
        <PriceList :fill_price="Pricegroup.wechat" :vip_price="Pricegroup.money" :image="Pricegroup.image"
          :TeamName="Pricegroup.team_name" :locationName="positionText" :type="'team'" :PaymentMethod="PaymentMethod">
        </PriceList>
      </view>
    </view>
    <!-- 确认信息 -->
    <view class="package" style="font-size: 30rpx;">
      <view class="space-between">
        <view>加注时间</view>
        <uni-datetime-picker v-model="datetimerange" type="datetimerange" rangeSeparator="至" @change="dateRange"
          :hide-second="true" :start-placeholder="'2023-2-26'">
          <view :style="{ color: indicate ? '#333' : '#888', textAlign: 'right', width: '100%' }">
            {{ indicate ? indicate : '请选择加注时间' }}
          </view>
        </uni-datetime-picker>
      </view>
      <view class="space-between top" @click="openPlatePicker">
        <view>车牌号</view>
        <view>
          <text :style="{ color: numberplate ? '#333' : '#808080' }">
            {{ numberplate ? numberplate : '请输入车牌号' }}
          </text>
          <uni-icons type="right" color="#999"></uni-icons>
        </view>
      </view>
      <view class="space-between top" style="align-items: flex-start;">
        <view>加注地址</view>
        <view @click="chooseLocation()" class="flex-end" style="width: 70%;text-align: right;">
          <view :style="{ color: Locposition ? '#333' : '#888' }">
            {{ Locposition ? Locposition : '请录入驻车地址' }}
          </view>
          <uni-icons type="location-filled" color="#999" size="24"></uni-icons>
        </view>
      </view>
      <view class="space-between top" style="align-items: flex-start;">
        <view>详细地址</view>
        <view>
          <textarea :placeholder="Detailed ? Detailed : '请输入驻车详细地址'" :value="Detailed" v-model="address"
            placeholder-style="color: #888;font-size: 29rpx" auto-height class="detail-textarea"></textarea>
        </view>
      </view>
    </view>
    <!-- 自定义加注金额 -->
    <CodeFilli :num="num" @activeTab="activeTab" :wechat_price="Pricegroup.wechat" :money_price="Pricegroup.money"
      :wechat_amount="Pricegroup.wechat_amount" :money_amount="Pricegroup.money_amount" @getdrivers="Calculation"
      :type="'team'" :state="'takeOut'" ref="CodeFilliRef" :Pricegroup="Pricegroup" @payForSub="payForSub"
      :PaymentMethod="PaymentMethod" :code="codeLoce"></CodeFilli>
    <!-- 底部支付 -->
    <CodeFilliBot :num="num" @takeOutSub="takeOutSub" :from_id="from_id" :state="'takeOut'" :type="'takeOut'"
      ref="takeOutBut" @getdrivers="Calculation" :fillamount="Pricegroup.wechat_amount"></CodeFilliBot>
  </view>
  <!-- 车牌弹框 -->
  <uni-popup ref="VehiclePlatePickerPopup" type="bottom" background-color="#fff">
    <VehiclePlatePicker :plate="numberplate" @add="toAddPlate" @pick="confirmPlate" />
  </uni-popup>
  <!-- 汽车车牌 -->
  <VehiclePlatePad v-if="isShowPlatePad" @cancel="isShowPlatePad = false" @confirm="confirmPlate" />
  <!-- 获取当前经纬度 -->
  <Lotlats @position="position"></Lotlats>
  <!-- 选择地图信息 -->
  <view v-if="curPage === 'map'"><web-view :src="mapURI"></web-view></view>
</template>

<script setup lang="ts">
  import { navBack } from '@/utils/navigator';
  import { getDriverID } from '@/stores/driverID';
  import TeamTop from '@c/canCode/TeamTop.vue';
  import PriceList from '@c/canCode/priceList.vue';
  import { errorToast, showToast, showLoading } from '@/utils/prompt';
  import Lotlats from '@c/team/Lotlat.vue';
  import CodeTop from '@c/canCode/codeTop.vue';
  import CodeFilli from '@c/canCode/CodeFilli.vue';
  import stepNav from '@c/canCode/StepNav.vue';
  import CodeFilliBot from '@c/canCode/CodeFilliBot.vue';
  import VehiclePlatePad from '@c/common/VehiclePlatePad.vue';
  import VehiclePlatePicker from '@c/appointment/VehiclePlatePicker.vue';
  import { useVehicleStore } from '@/stores/vehicle';
  import { getLog } from '@/gql/archives';
  import { takeawayPrice, getDriverPrice } from '@/gql/filling';
  import { GetCities } from '@/gql/team';
  import { toPublish } from '@mqtt';
  import { onLoad } from '@dcloudio/uni-app';
  import { decrypt } from '@/utils/jsencrypt';
  import { Ref, ref } from 'vue';
  /**
   * @component
   * @desc 外卖单页面
   * @property {Number} driver_id 用户ID
   * @property {Object} vehicleStore 车辆信息
   * @property {Number} longitude 当前位置的经度
   * @property {Number} latitude 当前位置的纬度
   * @property {String} Locposition 地址标题
   * @property {String} Detailed 详细地址
   * @property {String} address 自定义输入地址信息
   * @property {String} numberplate 车牌号
   * @property {Object} datetimerange 时间段
   * @property {String} indicate 显示加注时间段
   * @property {Number} from_id 待支付人ID
   * @property {Boolean} isShowPlatePad 是否显示添加车牌弹框
   * @property {Null} VehiclePlatePickerPopup 车牌号弹框
   * @property {Number} popupDelayClose 添加延迟时间
   * @property {Number} num 加注金额
   * @property {String} positionText 地址信息
   * @property {String} codeLoce 地址code
   * @property {Object} Pricegroup 加注金额信息
   * @property {Number} TakeoutRderID 外卖订单ID
   * @property {Object} information 外卖订单的所有信息
   * @property {String} takeOutBut 提交支付暂用值
   * @property {Number} lon 更改位置的经度
   * @property {Number} lat 更改位置的纬度
   * @property {String} curPage 选择地址状态
   * @property {String} mapURI 选择地址列表
   * @property {String} PaymentMethod 支付方式
   */
  const driver_id = getDriverID();
  const vehicleStore = useVehicleStore();
  vehicleStore.getPlateList();
  let longitude = 0; //纬度
  let latitude = 0; //经度
  const Locposition = ref(''); //地址标题
  const Detailed = ref(''); //详细地址
  const address = ref('');

  const numberplate = ref(''); //车牌号
  const datetimerange = ref();
  const indicate = ref(''); //加注时间段
  const from_id = ref(); //待支付人ID

  const isShowPlatePad = ref(false); //添加车牌弹框
  const VehiclePlatePickerPopup = ref(null); //车牌号弹框
  const popupDelayClose = 400; //添加延迟时间

  const num = ref(15); //加注金额

  const positionText = ref(''); //地址信息
  const codeLoce = ref(''); //地址code
  const Pricegroup : Ref<any> = ref({}); //加注金额信息

  const TakeoutRderID = ref(0); //外卖订单
  const information = ref({}); //外卖订单的所有信息

  const takeOutBut = ref(null); //提交支付暂用值
  const CodeFilliRef = ref(null);
  // 更改地址
  const lat = ref();
  const lon = ref();
  const curPage : Ref<'form' | 'map'> = ref('form');
  const mapURI = ref('');

  const repeat = ref(true)//放重复点击
  const PaymentMethod = ref('')
  onLoad(() => {
    const loct = uni.getStorageSync('StoreData')
    TakeoutRderID.value = loct && JSON.parse(decrypt(loct)).TakeoutRder ? JSON.parse(decrypt(loct)).TakeoutRder : 0
    init();
  });
  // 获取分享的加注订单信息
  function init() {
    showLoading();
    const payload = {
      query: getLog,
      variables: {
        id: Number(TakeoutRderID.value),
        driver_id,
      },
    };
    toPublish('ql/take/getLog', payload, (obj : any) => {
      const { data } = obj;
      information.value = data.getLog;
      if (data.getLog.starttime) {
        indicate.value = data.getLog.starttime.slice(5) + ' 至 ' + data.getLog.endtime.slice(5);
      }
      lat.value = data.getLog.latitude;
      lon.value = data.getLog.longitude;
      Locposition.value = data.getLog.locposition;
      Detailed.value = data.getLog.detailed;
      if (lat.value) {
        sub(lon.value, lat.value);
      }
      numberplate.value = data.getLog.cart_code ? data.getLog.cart_code : vehicleStore.plateList[0];
      // information.value.team_id=0
    });
  }
  /**
   * 计算团金额
   * @param {Number} price 支付金额
   */
  function TeamPrice(price : number) {
    if (!codeLoce.value) {
      return
    }
    showLoading();
    CodeFilliRef.value.num = price
    Pricegroup.value.wechat_amount = 0
    const payload = {
      query: takeawayPrice,
      variables: {
        team_id: information.value.team_id,
        code: codeLoce.value,
        price,
      },
    };
    toPublish('ql/take/getTeamPrice', payload, (obj : any) => {
      const { data } = obj;
      Pricegroup.value = data.getTeamPrice;
      num.value = price;
      if (price === 15) {
        CodeFilliRef.value.customLists()
      } else {
        setTimeout(() => {
          CodeFilliRef.value.bindChange()
        }, 100)
      }
      return
    });
  }
  /**
   * 普通用户计算金额
   * @param {Number} price 支付金额
   */
  function domesticPrice(price : number) {
    if (!codeLoce.value) {
      return
    }
    showLoading();
    Pricegroup.value.wechat_amount = 0
    CodeFilliRef.value.num = price
    const payload = {
      query: getDriverPrice,
      variables: {
        code: codeLoce.value,
        price,
      },
    };
    toPublish('ql/take/getDriverPrice', payload, (obj : any) => {
      const { data } = obj;
      Pricegroup.value = data.getDriverPrice;
      num.value = price;
      if (price === 15) {
        CodeFilliRef.value.customLists()
      } else {
        setTimeout(() => {
          CodeFilliRef.value.bindChange()
        }, 100)
      }
      return
    });
  }
  /**
   * 提交支付
   * @param {Object} type 支付方式
   * @param {Object} amount 加注量
   * @param {Object} price 加注单价
   */
  function payForSub(type : string, amount : number, price : number) {
    showLoading();
    takeOutBut.value.submit(type, amount, price)
  }
  /**
   * 提交加注订单
   * @param {Object} state 支付方式
   */
  function takeOutSub(state : any) {
    if (!numberplate.value) {
      showToast('请输入您的车牌号');
      return;
    }
    if (!lon.value) {
      showToast('请选择您的驻车地址');
      return;
    }
    const status = state.num;
    if (status == '2' && !from_id.value) {
      showToast('当前余额不足');
      return
    }
    const amount = status == 1 ? Pricegroup.value.wechat_amount : Pricegroup.value.money_amount;
    const price = status == 1 ? Pricegroup.value.wechat : Pricegroup.value.money;
    const pay_type = status == 1 ? 'mp' : 'money';
    const money_id = status == 1 ? '' : from_id.value;
    const plug_id = information.value ? Number(information.value.plug_id) : 0;
    const starttime = information.value.starttime
      ? information.value.starttime
      : datetimerange.value
        ? datetimerange.value[0]
        : '';
    const endtime = information.value.endtime
      ? information.value.endtime
      : datetimerange.value
        ? datetimerange.value[1]
        : '';
    const payload = {
      driver_id,
      longitude: lon.value,
      latitude: lat.value,
      locposition: Locposition.value,
      detailed: address.value ? address.value : Detailed.value,
      starttime,
      endtime,
      cart_code: numberplate.value,
      money: num.value,
      amount,
      price,
      plug_id,
      pay_type,
      money_id,
    };
    showLoading()
    if (!repeat.value) {
      return
    }
    repeat.value = false
    toPublish('take/addOrder', payload, (obj : any) => {
      const { code, msg, data } = obj;
      if (code === 1) {
        repeat.value = true
        if (status == 1) {
          takeOutBut.value.takeOutWeatch(data);
        } else {
          takeOutBut.value.takeMoney(data);
        }
      } else {
        repeat.value = true
        errorToast(msg);
      }
    });
  }
  /**
   * 获取当前城市信息
   * @param {Number} lat 当前位置的纬度
   * @param {Number} lot 当前位置的经度
   */
  function position(lats : number, lots : number) {
    longitude = lots;
    latitude = lats;
    if (!lat.value) {
      sub(lots, lats);
    }
  }
  /**
   * 获取当前位置信息
   * @param {Number} lon 当前驻车地址位置的经度
   * @param {Number} lat 当前驻车地址位置的纬度
   */
  function sub(lon : number, lat : number) {
    showLoading('正在加载');
    const payload = {
      query: GetCities,
      variables: {
        lon,
        lat,
      },
    };
    toPublish('ql/team/getCity', payload, (obj : any) => {
      uni.hideLoading();
      const { data } = obj;
      positionText.value = data.get_city.name;
      codeLoce.value = data.get_city.code;
      if (information.value.team_id === 0) {
        domesticPrice(15);
      } else {
        TeamPrice(15);
      }
    });
  }
  /**
   * 预约时间段
   * @param {Object} e 下次预约时间段
   */
  function dateRange(e : any) {
    datetimerange.value = e;
    const star = e[0].slice(5);
    const end = e[1].slice(5);
    indicate.value = star + ' 至 ' + end;
  }
  /**
   * @param {number} num 代付款人ID
   * @param {String} type 付款方式
   */
  function activeTab(num : number, type : string) {
    PaymentMethod.value = type
    from_id.value = num;
  }
  /**
   * 关闭车牌弹框
   */
  function toAddPlate() {
    closePlatePicker();
    isShowPlatePad.value = true;
  }
  /**
   * 选中车牌并关闭弹框
   * @param {String} plate 车牌号
   */
  function confirmPlate(plate : string) {
    numberplate.value = plate;
    setTimeout(() => {
      isShowPlatePad.value = false;
      closePlatePicker();
    }, popupDelayClose);
  }
  /**
   * 打开车牌弹框
   */
  function openPlatePicker() {
    VehiclePlatePickerPopup.value.open();
  }
  /**
   * 关闭车牌弹框
   */
  function closePlatePicker() {
    VehiclePlatePickerPopup.value.close();
  }
  /**
   * 选择支付金额
   * @param {Number} num 支付金额
   */
  function Calculation(num : number) {
    if (information.value.team_id === 0) {
      domesticPrice(num);
    } else {
      TeamPrice(num);
    }
  }
  /**
   *
   * 获取当前位置的地址列表
   */
  function chooseLocation() {
    mapURI.value = `https://apis.map.qq.com/tools/locpicker?coord=${latitude},${longitude}&search=1&type=1&key=URFBZ-F4TKI-SLPGX-57GMO-ZHYM6-BCFSL&referer=安蓝环保`;
    curPage.value = 'map';
    function msgListener(event : any) {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      const data = event.data;
      console.log(data);
      if (data && data.module == 'locationPicker') {
        //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
        // location.value = `${data.poiaddress}-${data.poiname}`;
        lon.value = Number(data.latlng.lng);
        lat.value = Number(data.latlng.lat);
        Detailed.value = data.poiaddress;
        Locposition.value = data.poiname;
        curPage.value = 'form';
        window.removeEventListener('message', msgListener);
        sub(lon.value, lat.value);
        num.value = 15;
      }
    }
    window.addEventListener('message', msgListener, false);
  }
</script>

<style scoped lang="less">
  .detail-textarea {
    text-align: right;
    // width: 70%;
  }

  .top {
    margin-top: 20rpx;
  }
</style>